// OneYear.cpp : implementation file
//

#include "stdafx.h"
#include "SwordBible.h"
#include "OneYear.h"
#include "BibleForm.h"
#include "BibleSheet.h"


// static variables
sword::SWModule* COneYear::pModulePlain[nBibles];

// COneYear dialog

IMPLEMENT_DYNAMIC(COneYear, CDialog)

COneYear::COneYear(CWnd* pParent /*=NULL*/)
	: CDialog(COneYear::IDD, pParent)
{
	pModuleActive = NULL;
	Index = 0;

}

COneYear::~COneYear()
{
}

void COneYear::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_RICHEDIT_ONEYEAR, m_oneyearRich);
	DDX_Control(pDX, IDC_ONEYEAR_VERSIONS, m_versionCtrl);
	DDX_Control(pDX, IDC_READINGLIST, ReadingListCtrl);
}


BEGIN_MESSAGE_MAP(COneYear, CDialog)
	ON_COMMAND(ID_ONEYEAR_PRINT,OnPrint)
	ON_COMMAND(ID_ONEYEAR_COPY, OnCopy)
	ON_COMMAND(ID_ONEYEAR_PREVIOUSDATE,OnPreviousDate)
	ON_COMMAND(ID_ONEYEAR_NEXTDATE,OnNextDate)
	ON_WM_SIZE()

	ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipNotify)
   ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipNotify)

	ON_CBN_SELCHANGE(IDC_ONEYEAR_VERSIONS, &COneYear::OnChangeVersions)
	ON_NOTIFY(MCN_SELECT, IDC_CALENDAR_ONEYEAR, &COneYear::OnSelectDate)
	ON_NOTIFY(MCN_SELCHANGE, IDC_CALENDAR_ONEYEAR, &COneYear::OnCalendarSelChange)
END_MESSAGE_MAP()


// COneYear message handlers

void COneYear::OnSize(UINT nType, int cx, int cy)
{
	CDialog::OnSize(nType, cx, cy);

	if(CalendarCtrl.GetSafeHwnd())
	CalendarCtrl.SetWindowPos(NULL,70,40,185,165,SWP_NOZORDER | SWP_NOACTIVATE);

	if(ReadingListCtrl.GetSafeHwnd())
	ReadingListCtrl.SetWindowPos(NULL,10,250,295,cy - 260,SWP_NOZORDER | SWP_NOACTIVATE);

         
	if(m_oneyearRich.GetSafeHwnd()) 
	m_oneyearRich.SetWindowPos(NULL,315,40,cx-325,cy-50,SWP_NOZORDER | SWP_NOACTIVATE);

      // position the version control
	if(m_versionCtrl.GetSafeHwnd())
		m_versionCtrl.SetWindowPos(NULL, 315, 10, 100 , 18,  SWP_NOZORDER | SWP_NOACTIVATE);


	
}

BOOL COneYear::OnInitDialog()
{
	CDialog::OnInitDialog();

	//set the icon for the dialog
	SetIcon(::AfxGetApp()->LoadIcon(IDR_MAINFRAME), TRUE);

	m_oneyearRich.SetBackgroundColor(FALSE, CColorMgr::RTFtoCOLORREF(CBiblePage::font.bg_color) );

	CString text = CBiblePage::font.GetHeaderRTF();
	

	for(int i = 0; i < 365; i++)
	{
	text += "\\par\\b " + CSwordBibleDoc::DailyReadings[i][0] + "  \\b0\\par " + 
		CSwordBibleDoc::DailyReadings[i][1] + " \\par ";
	
	}
	text += "}";

	
	
	ReadingListCtrl.SetParagraphCenter();
	ReadingListCtrl.SetRTF(text);

		// fill in the strings for different bible versions
	for(int i = 0; i < nBibles; i++)
		if(pModulePlain[i] != NULL)
			m_versionCtrl.AddString(pModulePlain[i]->Name());

	m_versionCtrl.SetCurSel(0);

	// set the active module
	int active = m_versionCtrl.GetCurSel();
	if(active >= 0) pModuleActive = pModulePlain[active];

	
    CTime time;
	CalendarCtrl.GetToday(time);

	// set the key
	int month  = time.GetMonth();
	int day = time.GetDay();
	
    Index =  0;
	for(int i = 0; i < month-1; i++) Index += CSwordBibleDoc::DaysInMonths[i];
	Index =Index +  day - 1;

    // show the day's bible text
	showText();
	
	
   // Create the control bars
	if(!m_wndFormatBar.Create(this)
						|| !m_wndFormatBar.LoadToolBar(IDR_ONEYEAR_TOOLBAR))
	{
					TRACE0("Failed to Create Dialog Toolbar\n");
					return -1;
	}
	
	
    EnableToolTips();   // enable tool tips for view
 
	m_wndFormatBar.SetBarStyle(m_wndFormatBar.GetBarStyle() |
		CBRS_TOOLTIPS | CBRS_FLYBY  );

	m_oneyearRich.SetEventMask(ENM_MOUSEEVENTS | ENM_KEYEVENTS | ENM_SCROLLEVENTS);

	
	//  Figure out how much room the control bars will take 
	// by using the reposQuery option of RepositionBars. 
	CRect rcClientStart;
    CRect rcClientNow;
    GetClientRect(rcClientStart);
    RepositionBars(AFX_IDW_CONTROLBAR_FIRST,
                   AFX_IDW_CONTROLBAR_LAST,
                   0, reposQuery, rcClientNow);



	// Move the controls in your dialog box to account for the space used 
	// by control bars at the top or left of the client area. If your dialog 
	// box contains a menu, you also need to account for the space used by the menu. 

	CPoint ptOffset(rcClientNow.left - rcClientStart.left,
                    rcClientNow.top - rcClientStart.top);
    CRect rcChild;
    CWnd* pwndChild = GetWindow(GW_CHILD);
    while (pwndChild)
    {
       pwndChild->GetWindowRect(rcChild);
       ScreenToClient(rcChild);
       rcChild.OffsetRect(ptOffset);
       pwndChild->MoveWindow(rcChild, FALSE);
       pwndChild = pwndChild->GetNextWindow();
    }
	

	// Increase the dialog box window dimensions by the amount of space used
	// by the control bars. 
	CRect rcWindow;
    GetWindowRect(rcWindow);
    rcWindow.right += rcClientStart.Width() - rcClientNow.Width();
    rcWindow.bottom += rcClientStart.Height() - rcClientNow.Height();
    MoveWindow(rcWindow, FALSE);

	

	// Position the control bars using RepositionBars. 
	RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);

	// Expand the size of the Toolbar window so all controls in it would fit	
	CRect toolBarRect;
	CToolBarCtrl& formatBar = m_wndFormatBar.GetToolBarCtrl();
	formatBar.GetWindowRect(toolBarRect);
	ScreenToClient(toolBarRect);
	toolBarRect.top += 4;
	toolBarRect.bottom += 4;
	toolBarRect.left = 315;
	toolBarRect.right += 600  ;
	formatBar.MoveWindow(toolBarRect,TRUE);

	m_wndFormatBar.ModifyStyle(0, TBSTYLE_FLAT);

	// diable the 16 ID_PLACEHOLDER BUTTONS
	for(int n = 0; n < 16; n++)
	formatBar.SendMessage((UINT) TB_ENABLEBUTTON, (WPARAM)(int) ID_PLACEHOLDER1 + n,  (LPARAM) MAKELONG(FALSE, 0) );


	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

// displays the text in the rich edit box of the one year bible
void COneYear::showText()
{
	
    if(!pModuleActive) return;

	
	sword::VerseKey vk;
	sword::ListKey lk = vk.ParseVerseList(CSwordBibleDoc::DailyReadings[Index][1], vk , TRUE);
	
		CString chapText = CBiblePage::font.GetHeaderRTF();
		

		CString titleSize;
		titleSize.Format("\\cf2\\fs%d ", CBiblePage::font.text_facesize + 5);
		chapText = chapText +  titleSize + "One Year Chronological Reading Plan [" + pModuleActive->Name() +
			"]" + "\\par Daily Reading for " + CSwordBibleDoc::DailyReadings[Index][0];
		
		// reset the font size
		titleSize.Format("\\fs%d", CBiblePage::font.text_facesize);
		chapText = chapText + titleSize + "\\par\\ ";

		lk = sword::TOP;
		sword::VerseKey key = lk;
		int chap = key.Chapter(), book = key.Book();
		int old_chap = -1, old_book = -1;
		CString Verse, Chapter;


				
	// get the text line by line
		for (lk = sword::TOP; !lk.Error(); lk++) {

		
			pModuleActive->SetKey(lk);         // set key to current verse
			key = lk;
			chap = key.Chapter();
		    book = key.Book();
			Verse.Format("%d",key.Verse());
		    Chapter.Format("%d",chap);
			


			if(   !(chap == old_chap && book == old_book)  )			
               	chapText += "\\par\\par\\cf1\\b " + (CString) key.getBookName() + " " + Chapter +  "\\b0\\par\\par ";
			


			// the verse use the color cf1 in the color table
			chapText = chapText +  "\\super\\cf1\\b "+ Verse + " \\b0\\nosupersub ";

			// the text uses the color cf2 in the color table
			chapText += "\\cf2 ";
			
			CString renderText = (CString) pModuleActive->RenderText();
			chapText += renderText;

			
		   old_chap = chap; old_book = book;
			


				
		}

		chapText += "}";
							
		m_oneyearRich.SetRTF(chapText);
		m_oneyearRich.SetFocus();
}



BOOL COneYear::OnToolTipNotify(UINT id, NMHDR *pNMHDR,   LRESULT *pResult)
{
   // need to handle both ANSI and UNICODE versions of the message
   TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
   TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
   CString strTipText;
   UINT nID = pNMHDR->idFrom;
   if (pNMHDR->code == TTN_NEEDTEXTA && (pTTTA->uFlags & TTF_IDISHWND) ||
      pNMHDR->code == TTN_NEEDTEXTW && (pTTTW->uFlags & TTF_IDISHWND))
   {
      // idFrom is actually the HWND of the tool
      nID = ::GetDlgCtrlID((HWND)nID);
   }

   char buf[100];

   if (nID != 0) // will be zero on a separator
   {AfxLoadString(nID,buf,100 ); strTipText.Format("%s",buf);  }

   if (pNMHDR->code == TTN_NEEDTEXTA)
      lstrcpyn(pTTTA->szText, strTipText, sizeof(pTTTA->szText));
   else
      _mbstowcsz(pTTTW->szText, strTipText, sizeof(pTTTW->szText));
   *pResult = 0;

   return TRUE;    // message was handled
}



void COneYear::OnPrint()
{
	CBibleForm::pControl = (CRichEditCtrl *) GetDlgItem(IDC_RICHEDIT_ONEYEAR);
	AfxGetMainWnd()->SendMessageToDescendants(WM_PRINT_CONTROL, (WPARAM) 1 , 0);
  
	
}

void COneYear::OnCopy(void) 
{
	m_oneyearRich.Copy();

}

void COneYear::OnPreviousDate()
{

   if(Index <= 0) Index = 364;
   else Index--;

    CTime time;
    CalendarCtrl.GetCurSel(time);          // Get current time
	time = time - CTimeSpan(1,0,0,0);
    CalendarCtrl.SetCurSel(time);   // set new time

	showText();   // update display

}

void COneYear::OnNextDate()
{
   if(Index >= 364) Index = 0;
   else Index++;

    CTime time;
    CalendarCtrl.GetCurSel(time);          // Get current time
	time = time + CTimeSpan(1,0,0,0);
	CalendarCtrl.SetCurSel(time);   // set new time

   showText();   // update display
	
}

void COneYear::OnChangeVersions()
{
		// set the active module
	int active = m_versionCtrl.GetCurSel();
	if(active >= 0) pModuleActive = pModulePlain[active];

	showText();


}



void COneYear::OnSelectDate(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMSELCHANGE pSelChange = reinterpret_cast<LPNMSELCHANGE>(pNMHDR);

	CTime time;
	CalendarCtrl.GetCurSel(time);

	// set the key
	int month  = time.GetMonth();
	int day = time.GetDay();
	
	
	Index = 0;
	for(int i = 0; i < month-1; i++) Index += CSwordBibleDoc::DaysInMonths[i];
	Index = Index + day - 1;

	showText();

	*pResult = 0;
}

void COneYear::OnCalendarSelChange(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMSELCHANGE pSelChange = reinterpret_cast<LPNMSELCHANGE>(pNMHDR);
	
	CTime time;
	CalendarCtrl.GetCurSel(time);

	// set the key
	int month  = time.GetMonth();
	int day = time.GetDay();
	
	
	Index = 0;
	for(int i = 0; i < month-1; i++) Index += CSwordBibleDoc::DaysInMonths[i];
	Index = Index + day - 1;

	showText();


	*pResult = 0;
}
